/**
 * Created by Administrator on 2017/6/21 0021.
 * Time: 10:24
 * 用途：webpack基础配置
 */
import "babel-polyfill"
import webpack from "webpack"
import glob from "glob"
import path from 'path'
import HtmlWebpackPlugin from "html-webpack-plugin"
import ExtractTextPlugin from "extract-text-webpack-plugin"
import CopyWebpackPlugin from "copy-webpack-plugin"
//开发配置
export const PATHS = {
    dist: path.resolve(__dirname, "sleep-mall-h5"),
    src: path.resolve(__dirname, 'src'),
    compassMixin: path.resolve(__dirname, "./node_modules/compass-mixins/lib"),
};

/**
 * 获取全部入口文件
 * @param globPath
 * @return {{}}
 */
function getEntries(globPath) {
    var files = glob.sync(globPath),
        entries = {};
    files.forEach(function (filepath) {
        var rootZ = filepath.split('/'),
            name = rootZ[rootZ.length - 1].replace(".js", "")
        entries[name] = filepath;
    });
    return entries;
}

var entries = getEntries('./src/js/entry/*.js'),
    chunks = Object.keys(entries);
export var baseConfig = function () {
    var self = this;
    var config = {
    
        devtool: self.sourceMap,
        //页面入口文件配置
        entry: {
//			libs: ["layer"] //分离第三方公共库
        },
        //插件项
        plugins: [
            //声明全局变量，无需引入
            new webpack.ProvidePlugin({
                layer:"layer-mobile"
            }),
            /*//webpack执行代码
             new webpack.optimize.CommonsChunkPlugin("common"),*/
            //提取重复的样式和脚本，重复出现大于1次的提取
            new webpack.optimize.CommonsChunkPlugin({
                name: "app",
                chunks: chunks,
                minChunks: 4,
                //children:true
            }),
            new ExtractTextPlugin({
                filename: 'css/[name][hash:8].css',
                allChunks: false
            }),
            new CopyWebpackPlugin([
                {
                    from:path.resolve(__dirname,"static"),
                    to:PATHS.dist
                }
            ]),
            //webpack-dev-server实时自动刷新
            new webpack.HotModuleReplacementPlugin()
        ],
        //入口文件输出配置
        output: {
            path: PATHS.dist,
            filename: 'js/[name][hash:8].js',
            //发布会被替换
            publicPath: self.publicPath
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    //启用babel-loader缓存编译结果选项，在重启webpack时不需要创新编译而是复用缓存结果减少编译流程
                    // loader: 'babel-loader?cacheDirectory',
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    include: path.resolve(__dirname, 'src')
                },
                {
                    test: /\.(scss|css)$/,
                    use: ExtractTextPlugin.extract({
                        fallback: 'style-loader',
                        //如果需要，可以在 sass-loader 之前将 resolve-url-loader 链接进来
                        use: "css-loader?importLoaders=2!postcss-loader!sass-loader",
                        publicPath: '../'
                    }),
                    exclude: path.resolve(__dirname,'./node_modules')
                },
                {
                    test: /\.(png|jpg|jpeg|gif)$/,
                    use: [{
                        loader: "url-loader",
                        query: {
                            name: "images/[name][hash:8].[ext]",
                            limit: 512
                        }
                    }]
                },
                //url-loader:字体图标加载器
                {
                    test: /\.(svg|woff|woff2|ttf|eot)$/,
                    loader: "url-loader",
                    query: {
                        name: "css/iconfont/[hash:8].[ext]",
                        limit: 512
                    }

                }, {
                    /*
                     匹配各种格式的图片和字体文件
                     上面html-loader会把html中<img>标签的图片解析出来, 文件名匹配到这里的test的正则表达式,
                     css-loader引用的图片和字体同样会匹配到这里的test条件
                     */
                    test: /\.html$/,
                    use: [{
                        loader: "html-loader",
                        query: {
                            minimize: false,
                            name: "images/[name]_[hash].[ext]",
                            limit: 512,
                            attrs:["img:src"],
                            interpolate:true
                        }
                    }]
                }
            ],
            noParse: [
                path.join(__dirname + '/node_modules/jquery/')
            ]
        },
        //其它解决方案配置
        resolve: {
            alias: {
                "@":PATHS.src,
                vue$: "vue/dist/vue.esm.js"
            },
            //为了减少搜索我们直接写明node_modules的全路径
            modules: [path.resolve(__dirname, 'node_modules')]
        }
    }
    !function () {
        //加载HtmlWebpackPlugin
        Object.keys(entries).forEach(function (name) {
            // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
            config.entry[name] = entries["babel-polyfill",name];
            // 每个页面生成一个html
            var pluginForHtml = new HtmlWebpackPlugin({
                // 生成出来的html文件名
                filename: `${PATHS.dist}/${name}.html`,
                // 每个html的模版，这里多个页面使用同一个模版
                template: `${PATHS.src}/page/${name}.html`,
                // 自动将引用插入html
                inject: true,
                hash: false,
//                favicon: "./src/images/favicon.ico",
                chunksSortMode: function (chunk1, chunk2) {
                    var order = ["app", name];
                    var order1 = order.indexOf(chunk1.names[0]);
                    var order2 = order.indexOf(chunk2.names[0]);
                    return order1 - order2;
                },
                // 每个html引用的js模块，common.js公共模块抽取
                //对应entry公共模块的自定义抽取
                chunks: ["app", name]
            });
            config.plugins.push(pluginForHtml);
        })
    }();
    return config;
};